//
//  TSPasswordEditViewController.m
//  chart
//
//  Created by xu on 15/8/22.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSPasswordEditViewController.h"
#import "TSToolBarTextField.h"

#define SEARCH_LABEL_WIDTH  70.f
#define SEARCH_LABEL_HEIGHT 35.f
#define SEARCH_ROW_GAP 10.f

@interface TSPasswordEditViewController ()

@end

@implementation TSPasswordEditViewController{
    TSToolBarTextField *oldPwdTextField;
    TSToolBarTextField *newPwdTextField;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setTitle:@"更改密码"];
    
    [self addOldPwdRow];
    
    [self addNewPwdRow];
    
    WS(weakSelf);
    [self rightBarButtonWithTitle:@"修改" barNorImage:nil barHltImage:nil action:^{
        if (!weakSelf) {
            return;
        }
        
        [weakSelf editUserPassword];
    }];
}

- (void)editUserPassword
{
    if ([TSTools isEmpty:oldPwdTextField.text] || [TSTools isEmpty:newPwdTextField.text]) {
        [[LBToastManager manager] showtoast:@"密码不能为空"];
        
        return;
    }
    
    WS(weakSelf);
    [[TSUserModel sharedInstance] modifyPwd:oldPwdTextField.text andNewPwd:newPwdTextField.text completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (UILabel *)createLabel:(CGRect)frame Title:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    [label setText:title];
    [label setFont:FONT(12.f)];
    
    return label;
}

- (TSToolBarTextField *)createTextField:(CGRect)frame Title:(NSString *)title
{
    TSToolBarTextField *text_field = [[TSToolBarTextField alloc] initWithFrame:frame];
    [text_field setText:title];
    [text_field.layer setBorderWidth:.5f];
    [text_field.layer setCornerRadius:.5f];
    [text_field setSecureTextEntry:YES];
    return text_field;
}

- (void)addOldPwdRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, MARGIN_TOP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"旧密码:"];
    [self.view addSubview:label];
    
    oldPwdTextField = [self createTextField:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), currentDeviceWidth-2*MARGIN_LEFT-SEARCH_LABEL_WIDTH-10.f, SEARCH_LABEL_HEIGHT) Title:@""];
    [self.view addSubview:oldPwdTextField];
}

- (void)addNewPwdRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(oldPwdTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"新密码:"];
    [self.view addSubview:label];
    
    newPwdTextField = [self createTextField:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), currentDeviceWidth-2*MARGIN_LEFT-SEARCH_LABEL_WIDTH-10.f, SEARCH_LABEL_HEIGHT) Title:@""];
    [self.view addSubview:newPwdTextField];
}

@end
